from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializers import BookInfoModelSerializer
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.authentication import SessionAuthentication,BasicAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser
from rest_framework.throttling import AnonRateThrottle


#视图集
class BookModelViewSet(ModelViewSet):
    """
    list:
        获取所有数据
    create:
        创建单个数据
    bread_book：
        获取指定数据
    read ：
        获取单个数据
    update：
        修改单个数据
    partial_update：
        局部更新
    delete：
        删除
    update_book_bread：


    """
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer
    #获取阅读量大于20的

    #1.认证，局部变量
    # authentication_classes = [SessionAuthentication, BasicAuthentication]
    #2.权限，局部变量
    # permission_classes = [IsAuthenticated]#普通用户
    # permission_classes = [AllowAny]　#所有用户
    # permission_classes = [IsAdminUser]　#管理员
    #3.限流　，局部变量
    # throttle_classes = [AnonRateThrottle] #对匿名用户限流
    #4.可选限流
    # throttle_scope = 'downloads' #对下载限流

    @action(methods=['GET'],detail=False) #生成路由规则：book(前缀)/bread_book(方法名)  detail=False　不需要带参数
    def bread_book(self,request):
        #获取指定书籍
        books=BookInfo.objects.filter(bread__gt=100)
        #创建序列化器对象
        serializer=self.serializer_class(instance=books,many=True)
        #返回数据
        return Response(serializer.data)
    @action(methods=['PUT'],detail=True)#生成路由规则：book(前缀)/(?P<pk>[^/.]+)(参数)/update_book_bread(方法名)/
    def update_book_bread(self,request,pk):
        book = self.get_object()
        data = request.data
        serializer = self.get_serializer(instance=book,data=data,partial = True)

        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data,status=201)
